package com.yf.boot.ability.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.yf.boot.ability.oss.service.OssService;
import com.yf.boot.ability.upload.utils.OssUtils;
import com.yf.boot.base.api.api.ApiError;
import com.yf.boot.base.api.exception.ServiceException;
import com.yf.boot.base.api.utils.StringUtils;
import com.yf.modules.sys.config.dto.CfgUploadOssDTO;
import com.yf.modules.sys.config.service.CfgUploadOssService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * OSS业务类
 *
 * @author bool
 */
@Log4j2
@Service
public class OssServiceImpl implements OssService {


    private static final String CTV_TEMPLATE = "S00000001-200000";


    @Autowired
    private CfgUploadOssService cfgUploadOssService;

    @Override
    public String upload(String localFile) {

        // 获取配置文件
        CfgUploadOssDTO conf = cfgUploadOssService.find();

        // 安排上传后的文件名
        String ossPath = OssUtils.processPath(localFile);

        log.error("安排文件名：{}", ossPath);

        // 上传文件
        try {
            this.putObject(conf, ossPath, new FileInputStream(localFile));
            log.error("文件推送成功：{}", ossPath);
        } catch (IOException e) {
            e.printStackTrace();
            //文件异常
            throw new ServiceException(ApiError.ERROR_10010001);
        }

        //返回结果
        return conf.getUrl() + ossPath;
    }


    /**
     * 获得上传实例
     * @return
     */
    private OSSClient getClient(CfgUploadOssDTO conf){

        if(conf == null
                || StringUtils.isBlank(conf.getAccessKeyId())
                || StringUtils.isBlank(conf.getAccessKeySecret())
                || StringUtils.isBlank(conf.getEndpoint())){
            throw new ServiceException("OSS配置文件错误！");
        }

        // 鉴权
        CredentialsProvider credentials = new DefaultCredentialProvider(conf.getAccessKeyId(), conf.getAccessKeySecret());

        // 初始化上传节点，数据库未配置节点信息
        return new OSSClient(conf.getEndpoint() + ".aliyuncs.com", credentials, null);
    }


    /**
     * 获得上传实例
     * @return
     */
    private void putObject(CfgUploadOssDTO conf, String filePath, InputStream is){

        // 配置文件属性
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setCacheControl("max-age=31536000");
        // 上传文件
        this.getClient(conf).putObject(conf.getBucket(), filePath, is, metadata);
    }
}
